package ru.spies.loginOrRegistration;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;

import ru.spies.forms.LoginOrRegistrationForm;

public abstract class AbstractLoginOrRegistrationWork {

	private static final String RETURN_HOME="<input type=\"button\" class=\"inFormBtn\" onclick=\"goHome()\" value=\"Вернуться на главную\">";
	private static final String CREATION_ERROR="<p>Ошибка при создании формы!</p>"+RETURN_HOME;
	protected static final String EMPTY_LOGIN="<p>Не введен логин!</p>"+RETURN_HOME;
	protected static final String EMPTY_PASSWORD="<p>Не введен пароль!</p>"+RETURN_HOME;
	protected static final String WRONG_LOGIN_OR_PASSWORD="<p>Неверный логин или пароль!</p>";
	
	
	private static final String COOKIE_LOGIN="LOGIN";	
	private static final String COOKIE_REGISTRATION="REGISTRATION";	
	private static final String COOKIE_DO_REGISTRATION="DO_REGISTRATION";		
	private static final String COOKIE_EXIT="EXIT";
	private static final String COOKIE_NAME="loginOrRegistration";
	
	private static final int WAS_LOGIN=0;	
	private static final int WAS_REGISTRATION=1;	
	private static final int WAS_DO_REGISTRATION=2;	
	private static final int WAS_EXIT=3;
		
	protected abstract String createForm(HttpServletRequest request);
	
	public static String getWork(HttpServletRequest request){
		AbstractLoginOrRegistrationWork abstractWork;
		switch (readCookie(request)) {
		case WAS_LOGIN:
			abstractWork = LoginWork.getInstance();
			break;
		case WAS_REGISTRATION:
			abstractWork = PrepareRegistrationWork.getInstance();
			break;
		case WAS_EXIT:
			abstractWork = ExitWork.getInstance();
			break;
		case WAS_DO_REGISTRATION:
			abstractWork = RegistrationWork.getInstance();
			break;
		default:
			abstractWork = null;
		}
		if (abstractWork==null){
			return LoginOrRegistrationForm.getInstance().createFailureForm(CREATION_ERROR);
		}
		return abstractWork.createForm(request);
	}
	
	private static int readCookie(HttpServletRequest request){
		Cookie cookies[] = request.getCookies();
		if (cookies==null){
			return -1;
		}
		for(Cookie i:cookies){
			if (i.getName().equals(COOKIE_NAME)){
				if (i.getValue().equals(COOKIE_LOGIN)){
					return WAS_LOGIN;
				}
				if (i.getValue().equals(COOKIE_EXIT)){
					return WAS_EXIT;
				}
				if (i.getValue().equals(COOKIE_REGISTRATION)){
					return WAS_REGISTRATION;
				}
				if (i.getValue().equals(COOKIE_DO_REGISTRATION)){
					return WAS_DO_REGISTRATION;
				}
			}
			
		}
		return -1;
	}

}
